<!--
 @description PopPicker
 @fileName index.vue
 @author zengqiongying
 @created 2022/08/02 09:19:38
-->
<template>
  <Popup
    v-model="popShow"
    position="bottom"
    :title="title"
    :show-cancel-button="false"
    @confirm="handleSubmit"
  >
    <van-picker
      :show-toolbar="false"
      :columns="columns"
      :default-index="defaultIndex"
      :item-height="54"
      @change="onChange"
    />
  </Popup>
</template>

<script>
import Popup from '@/components/Popup'
export default {
  name: 'PopPicker',
  components: { Popup },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default: () => []
    },
    value: {
      type: String,
      default: ''
    }, // 选中的值
    lable: {
      type: String,
      default: ''
    }, // 选中的值的名称
    valueName: {
      // 选项值键名
      type: String,
      default: 'id'
    },
    lableName: {
      // 选项名称键名
      type: String,
      default: ''
    }
  },
  data() {
    return {
      columns: [],
      defaultIndex: 0, // 默认选中项索引
      curIndex: 0 // 当前选中项索引
    }
  },

  computed: {
    popShow: {
      set(val) {
        this.$emit('update:show', val)
      },
      get(val) {
        return this.show
      }
    }
  },
  watch: {
    value(val) {
      if (val) {
        const index = this.list.findIndex(v => v[this.valueName] === val)
        this.curIndex = index === -1 ? 0 : index
      } else {
        this.curIndex = 0
        this.$emit('input', '')
        this.$emit('update:lable', '')
      }
    },
    list: {
      handler(val) {
        this.initListData()
      },
      deep: true
    }
  },
  created() {
    this.initListData()
  },
  methods: {
    initListData() {
      this.columns = this.list.map((v, index) => {
        if (this.value === v[this.valueName]) {
          this.curIndex = index
          this.defaultIndex = index
        }
        return v[this.lableName]
      })
    },
    onChange(el, value, index) {
      this.curIndex = index
    },
    handleSubmit() {
      const obj = this.list[this.curIndex]
      if (!(obj && obj[this.valueName])) {
        this.$toast('请选择')
        return
      }
      const value = obj[this.valueName] || ''
      const lable = obj[this.lableName] || ''
      this.$emit('input', value)
      this.$emit('update:lable', lable)
      this.$emit('selectChange', obj)
      this.popShow = false
    }
  }
}

</script>
<style lang='less' scoped>
  /deep/ [class*=van-hairline]::after{
    border-color: #00C8B4;
    border-width: 2px 0;
  }
  /deep/ .van-picker-column__item--selected{
    font-size: 18px;
    font-weight: bold;
  }
</style>
